import typing

from sqlalchemy.orm import sessionmaker

from autotest.exceptions.exceptions import ParameterError
from autotest.schemas.api.data_factory import ApiQuery, DfApiIn, DfApiQuery, DfApiListQuery
from autotest.models.data_factory_cp import DataFactoryApi, DataFactoryOrg
from autotest.db.db_depends import execute_sql, DataBase,add_sql,update_sql
from sqlalchemy.engine import Connection


class DfApiService:
    @staticmethod
    async def list(params: DfApiListQuery) -> typing.Dict:
        """
        接口列表
        :param params:
        :return:
        """
        data = await DataFactoryApi.get_list_by_org(params)
        return data

    @staticmethod
    async def detail(params: DfApiQuery) -> typing.Dict:
        data = await DataFactoryApi.get(id=params.id)
        return data

    @staticmethod
    async def save_or_update(params: DfApiIn) -> typing.Dict:
        """
        更新保存测试用例/配置
        :param params:
        :return:
        """
        if not params.sence_name:
            raise ParameterError("用例名不能为空!")
        # 判断用例名是否重复
        existing_data = await DataFactoryApi.get_dfapi_by_name(sence_name=params.sence_name)
        mod = None
        if params.id:
            api_info = await DataFactoryApi.get(params.id)
            if not api_info:
                raise ParameterError("用例不存在!")
            if api_info.sence_name != params.sence_name:
                if existing_data:
                    raise ParameterError("用例名重复!")
        data = await DataFactoryApi.create_or_update(params.dict())
        return await DataFactoryApi.get_api_by_id(data.get('id', None))

    @staticmethod
    async def deleted(id: typing.Union[int, str]):
        """
        删除api，支持硬删和软删
        :param id:
        :return:
        """
        return await DataFactoryApi.delete(id=id)

    @staticmethod
    async def dependsTest(db: sessionmaker):
        """
        查询
        """
        # sql = "select * from student"
        sql = "select * from student where id=2"
        result = execute_sql(session=db, sql=sql, all=True)
        return result

    @staticmethod
    async def dependsTestAdd(db: sessionmaker):
        """
        新增
        """
        # sql = "select * from student"
        # result = execute_sql(session=db, sql=sql, all=True)

        sql = f"insert into student(name,pwd,sno,sex,clas_id) values ('新增','www',111,1,13)"
        result = add_sql(session=db, sql=sql)
        return result

    @staticmethod
    async def dependsTestUpdate(db: sessionmaker):
        """
        新增
        """
        # sql = "select * from student"
        # result = execute_sql(session=db, sql=sql, all=True)

        sql = f"update student set name = 'erain' where id = 2"
        result = update_sql(session=db, sql=sql)
        return result